package com.zhangmeng.online.exam.ui.components;

import com.zhangmeng.online.exam.ui.utils.ApiUtils;
import com.zhangmeng.online.exam.ui.api.DataLoad;
import com.zhangmeng.online.exam.ui.components.callBack.DynamicTableComponentCallBack;
import com.zhangmeng.online.exam.ui.utils.AlertUtils;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.*;
import javafx.scene.control.cell.MapValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import org.casic.javafx.control.PaginationPicker;

import java.util.*;


/**
 * 动态表格
 *
 * @author zm
 * @date 2025/3/5 15:17
 * @version: 1.0
 */
public class DynamicTableComponent extends VBox {

    private HeaderComponent headerComponent;

    private DynamicTableComponentCallBack callBack;

    private TableView<Map<String, SimpleStringProperty>> tableView;

    public TableView<Map<String, SimpleStringProperty>> getTableView() {
        return tableView;
    }

    public void setTableView(TableView<Map<String, SimpleStringProperty>> tableView) {
        this.tableView = tableView;
    }

    private DataLoad dataLoad;

    public DataLoad getDataLoad() {
        return dataLoad;
    }

    public void setDataLoad(DataLoad dataLoad) {
        this.dataLoad = dataLoad;
    }

    public DynamicTableComponentCallBack getCallBack() {
        return callBack;
    }

    public void setCallBack(DynamicTableComponentCallBack callBack) {
        this.callBack = callBack;
    }

    private final ObservableList<Map<String, SimpleStringProperty>> data = FXCollections.observableArrayList();

    public ObservableList<Map<String, SimpleStringProperty>> getData() {
        return data;
    }

    //新增编辑删除表单是否显示(增删该)
    private final SimpleBooleanProperty isForm = new SimpleBooleanProperty(true);

    //    public DynamicTableComponent(List<Map<String, SimpleStringProperty>> dataList,List<String> keys) {
    public DynamicTableComponent(ApiUtils.DataView dataView,boolean showForm) {
        super();
        this.isForm.set(showForm);
        this.dataLoad = dataView.getDataLoad();
        List<Map<String, SimpleStringProperty>> dataList = dataView.getDataList();
        List<String> keys = dataView.getKeys();
        tableView = new TableView<>();
        tableView.setItems(data);
        tableView.setEditable(true);
        tableView.prefHeightProperty().bind(this.heightProperty());
        tableView.prefWidthProperty().bind(this.widthProperty());
        // 动态生成列（示例字段）‌:ml-citation{ref="3,4" data="citationList"}
        List<String> columns = keys.stream().filter(key -> !key.equals("id")).toList();
//        if (!dataList.isEmpty()){
//            columns= Arrays.asList(dataList.get(0).keySet().toArray(new String[0])).stream().filter(key -> !key.equals("id")).toList();
//        }else {
//            columns=keys;
//        }
        columns.forEach(col -> {
            TableColumn<Map<String, SimpleStringProperty>, String> column = new TableColumn<>(col);
            // 数据绑定‌:ml-citation{ref="1,3" data="citationList"}
            column.setCellValueFactory(new MapValueFactory(col));
            // 启用单元格编辑‌:ml-citation{ref="4,5" data="citationList"}
            column.setCellFactory(TextFieldTableCell.forTableColumn());
            column.setOnEditCommit(event -> {
                Map<String, SimpleStringProperty> row = event.getRowValue();
                Set<Map.Entry<String, SimpleStringProperty>> entries = row.entrySet();
                String name = null;
                for (Map.Entry<String, SimpleStringProperty> entry : entries) {
                    String key = entry.getKey();
                    SimpleStringProperty value = entry.getValue();
                    if (key.startsWith(col + "_")) {
                        name = key.split("_")[1];
                        break;
                    }
                }
                // 刷新数据

                if (name != null) {
                    String newValue = event.getNewValue();
                    String oldValue = event.getOldValue();
                    // 调用接口修改数据
                    callBack.update(DynamicTableComponent.this, row.get("id").get(), name, oldValue, newValue);
                    // 刷新界面
                    row.get(col).set(event.getNewValue());

                } else {
                    AlertUtils.alert_msg("该列不允许修改!");
                    flushData();
                }
            });

            column.prefWidthProperty().bind(tableView.widthProperty().divide(columns.size()));

            tableView.getColumns().add(column);
        });
        data.addAll(dataList);

        ContextMenu contextMenu = new ContextMenu();

        if (dataLoad.getContextMenu() != null && !dataLoad.getContextMenu().isEmpty()){
            contextMenu.getItems().addAll(dataLoad.getContextMenu());
        }

        if (isForm.get()){

            MenuItem editItem = new MenuItem("编辑");

            editItem.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    Map<String, SimpleStringProperty> selectedItem = tableView.getSelectionModel().getSelectedItem();
                    if (selectedItem != null) {
                        SimpleStringProperty id = selectedItem.get("id");
                        if (id != null) {
                            callBack.edit(id.get(), DynamicTableComponent.this);
                        }
                    }
                }
            });


            MenuItem deleteItem = new MenuItem("删除");
            deleteItem.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    Map<String, SimpleStringProperty> selectedItem = tableView.getSelectionModel().getSelectedItem();
                    if (selectedItem != null) {
                        SimpleStringProperty id = selectedItem.get("id");
                        if (id != null) {
                            callBack.delete(id.get());
                        }
                    }
                    data.remove(tableView.getSelectionModel().getSelectedItem());
                }
            });

            contextMenu.getItems().addAll(editItem, deleteItem);

            ///添加按钮
            Button button = new Button("新增");
            button.setOnAction(event -> {
                Stage window = (Stage) this.getScene().getWindow();
                callBack.Add(callBack.getAddForm(), window, this);
            });
            this.getChildren().add(button);
        }



       tableView.setContextMenu(contextMenu);


        tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);//允许一次选择一个或多个连续的索引范围。

        this.setSpacing(10);

        if (headerComponent != null){
            this.getChildren().add(headerComponent);
        }

        this.getChildren().addAll(tableView);

        //初始化一个分页
        PaginationPicker paginationPicker = new PaginationPicker();
        paginationPicker.setTotal(dataView.getTotal());//设置总数据量，默认0
        paginationPicker.setPageSize(dataView.getPageSize());//设置每页显示条数，默认30
        paginationPicker.setPageButtonCount(9);//设置页码按钮的数量，默认7，当总页数超过该值时会折叠，大于等于 5 且小于等于 21 的奇数
        paginationPicker.setCurrentPage(dataView.getPageNum());//设置当前选择页码，默认第一页（注意：必须放在所有设置条件之后）。不小于0 并且 不大于总页数
        paginationPicker.setPaginationButtonFontSize(12);//设置分页字体大小，默认10(不小于2)
        //监听点击动作事件
        paginationPicker.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
//                System.out.println("当前选择页码："+paginationPicker.getCurrentPage());
                data.clear();
                data.addAll(callBack.flushData(paginationPicker.getCurrentPage(), paginationPicker.getPageSize()).getDataList());
            }
        });
        this.getChildren().add(paginationPicker);
    }

    public void flushData() {
        data.clear();
        data.addAll(callBack.flushData(ApiUtils.PAGE_NUM, ApiUtils.PAGE_SIZE).getDataList());
    }

    public HeaderComponent getHeaderComponent() {
        return headerComponent;
    }

    public void setHeaderComponent(HeaderComponent headerComponent) {
        this.headerComponent = headerComponent;
    }

    public void setIsForm(boolean isForm) {
        this.isForm.set(isForm);
    }
}
